<!DOCTYPE html>
<html>
<head>
    <title>Advanced WebSocket Debug</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        .log { background: #f5f5f5; padding: 10px; border-radius: 5px; margin: 10px 0; }
        .error { color: red; }
        .success { color: green; }
        .info { color: blue; }
        button { padding: 10px 20px; margin: 5px; }
    </style>
</head>
<body>
    <h1>Advanced WebSocket Connection Debug</h1>
    
    <div>
        <button id="connectBtn">Connect to WebSocket</button>
        <button id="disconnectBtn">Disconnect</button>
        <button id="sendUserJoinBtn">Send User Join</button>
    </div>
    
    <div id="status" class="log">Not connected</div>
    <div id="logs" class="log"></div>

    <script>
        let socket = null;
        let connectionAttempts = 0;
        
        document.getElementById('connectBtn').addEventListener('click', connectWebSocket);
        document.getElementById('disconnectBtn').addEventListener('click', disconnectWebSocket);
        document.getElementById('sendUserJoinBtn').addEventListener('click', sendUserJoin);
        
        function log(message, type = 'info') {
            const logsDiv = document.getElementById('logs');
            const timestamp = new Date().toLocaleTimeString();
            logsDiv.innerHTML += `<div class="${type}">[${timestamp}] ${message}</div>`;
            logsDiv.scrollTop = logsDiv.scrollHeight;
            console.log(`[${type}] ${message}`);
        }
        
        function connectWebSocket() {
            const statusDiv = document.getElementById('status');
            
            if (socket && socket.readyState === WebSocket.OPEN) {
                log('Already connected', 'info');
                return;
            }
            
            connectionAttempts++;
            log(`Connection attempt #${connectionAttempts}`, 'info');
            statusDiv.textContent = `Connecting... (Attempt ${connectionAttempts})`;
            
            try {
                // 连接到WebSocket服务器
                socket = new WebSocket('ws://localhost:3000');
                log('WebSocket object created', 'info');
                
                socket.onopen = () => {
                    log('WebSocket connection opened', 'success');
                    statusDiv.textContent = 'Connected';
                };
                
                socket.onmessage = (event) => {
                    log(`Received message: ${event.data}`, 'info');
                    console.log('Raw message:', event.data);
                    
                    try {
                        const data = JSON.parse(event.data);
                        log(`Parsed message type: ${data.type || 'unknown'}`, 'info');
                        
                        if (data.type === 'connected') {
                            log(`Server welcome message: ${data.message}`, 'success');
                        }
                    } catch (e) {
                        log(`Error parsing message: ${e.message}`, 'error');
                    }
                };
                
                socket.onclose = (event) => {
                    log(`WebSocket connection closed. Code: ${event.code}, Reason: ${event.reason}`, 'error');
                    statusDiv.textContent = 'Disconnected';
                    
                    // 如果是异常断开，尝试重连
                    if (event.code !== 1000) { // 1000是正常关闭
                        log('Abnormal disconnection, will try to reconnect in 3 seconds...', 'error');
                        setTimeout(connectWebSocket, 3000);
                    }
                };
                
                socket.onerror = (error) => {
                    log(`WebSocket error: ${error.message}`, 'error');
                    statusDiv.textContent = 'Error';
                };
            } catch (e) {
                log(`Failed to create WebSocket: ${e.message}`, 'error');
                statusDiv.textContent = 'Connection Failed';
            }
        }
        
        function disconnectWebSocket() {
            if (socket) {
                log('Disconnecting...', 'info');
                socket.close(1000, 'User requested disconnect');
            }
        }
        
        function sendUserJoin() {
            if (!socket || socket.readyState !== WebSocket.OPEN) {
                log('Not connected to WebSocket', 'error');
                return;
            }
            
            const userJoinMessage = {
                type: 'user-join',
                user: { 
                    id: `debug_user_${Date.now()}`, 
                    name: 'Debug User', 
                    color: '#FF0000',
                    documentId: 1
                }
            };
            
            try {
                socket.send(JSON.stringify(userJoinMessage));
                log('Sent user-join message', 'info');
            } catch (e) {
                log(`Error sending message: ${e.message}`, 'error');
            }
        }
    </script>
</body>
</html>